package com.syncomponents.support;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

/**
 * xml解析类
 * 
 * @author sunkey
 * @date Jan 14, 2014
 */
public class XMLParser {

    /**
     * 解析
     * @param xmlPath path of the desired resource
     * @param classesToBeBound list of java classes to be recognized by the new JAXBContext. Can be empty, in which case a JAXBContext that only knows about spec-defined classes will be returned.
     * @return 解析后实体集合
     * @throws JAXBException
     * @throws IOException
     */
    public static  Object parse(String xmlPath, Class<?>... classesToBeBound) throws JAXBException, IOException {
        JAXBContext context = JAXBContext.newInstance(classesToBeBound);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        URL url = XMLParser.class.getResource(xmlPath);
        Object object = unmarshaller.unmarshal(url.openStream());
        return object;
    }

    /**
     * 转换成资源实体map集合
     * @param obj 解析后的资源实体集合
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T extends ResourceBean> Map<String, T> convertToResources(Object obj) {
        Map<String, T> map = new HashMap<String, T>();
        BeanList<T> list = (BeanList<T>) obj;
        for (T resource : list) {
            map.put(resource.getAction(), resource);
        }
        return map;
    }
}
